import { _decorator, Component, Node, UITransform, Input, EventTouch, instantiate } from 'cc';
import CCUtils from '../util/CCUtils';
import GameUtils from '../util/GameUtils';
import { CardItem } from './CardItem';
import { allColumn, gameConst, LayerInfo, typeArryAll } from './GameConst';
import { gameManager } from './GameManager';
import { PosInfo } from './PosInfo';
const { ccclass, property } = _decorator;

@ccclass('LayerItem')
export class LayerItem extends Component {


    // public bg:GImage = null;
    private content:Node = null;
    // private waitContent:Node = null;
    private content_UITransform:UITransform = null;
    // private waitContent_UITransform:UITransform = null;

    private static baseLayarId:number = 1;

    public info:LayerInfo = null;

    onLoad(){
        // this.bg = CCUtils.getGImage(this.node,"bg");
        this.content = CCUtils.findChild(this.node,"content");
        // this.waitContent = CCUtils.findChild(this.node,"waitContent");
        this.content_UITransform = this.content.getComponent(UITransform);
        // this.waitContent_UITransform = this.waitContent.getComponent(UITransform);

        // console.log(`初始化地图信息，总宽${this.allWidth}，总高${this.allHeight}，格子宽${cellWidth}，格子高${cellHeight},列数${allColumn}，行数${allRow}`)

    }


    /**
     * 初始化
     * @param type 
     * @param pos 
     */
    public init() {
        this.info = {layerId:LayerItem.baseLayarId, allCards:new Map<string, CardItem>()};
        LayerItem.baseLayarId ++;

        let pixelX = (this.info.layerId%10)*3; //不同layer的层偏移量，好看一点，不会完全覆盖
        let pixelY =  - (this.info.layerId%10)*3; //不同layer的层偏移量，好看一点，不会完全覆盖
        this.node.setPosition(pixelX, pixelY); 
        
        // this.bg.loadSpriteFrame(`ui/bg${this.info.layerId%10}/spriteFrame`);
    }


    /**
     * 添加一些卡牌
     */
    public addSomeCard(cardNum:number) {
        for (let index = 0; index < cardNum; index++) {
            this.addOneCard();
        }
        
    }


    /**
     * 添加一个卡牌
     * @param pos 位置，没就随机一个
     * @param type 类型，没就随机一个
     * @returns 
     */
    public addOneCard(pos?:PosInfo,type?:number):CardItem {

        if (pos == null) { //随机给一个
            pos = GameUtils.getRandomPos(this.info);
        }
        if (type == null) { //随机给一个
            type = GameUtils.getRandomOne(typeArryAll);
        }

        let card:Node = instantiate(gameConst.globelPrefab.cardPrefab);
        let citem:CardItem = card.getComponent(CardItem);
        this.content.addChild(card);
        card.active = true;
        citem.init(this.info,type);
        citem.setPos(pos);
        this.info.allCards.set(`${pos.gridX}_${pos.gridY}`, citem);

        card.on(Input.EventType.TOUCH_START, this.onClickCard, this);

        gameManager.updateCardCoverByAddCard(citem);

        return citem;
    }


    private onClickCard(e:EventTouch) {

        if (gameManager.isSelectContainerFull()) {
            return;
        }

        let clickItem:CardItem = e.currentTarget.getComponent(CardItem);  
        if (clickItem.beCover == true) {
            return;
        }
        clickItem.node.removeFromParent();
        this.info.allCards.delete(`${clickItem.pos.gridX}_${clickItem.pos.gridY}`);
        gameManager.selectCard(clickItem);

    }

    /**
     * 检查当前layer有没有覆盖了需要检查的卡牌，默认需要检查的卡牌在当前层级之下
     * true：覆盖了。
     */
    public checkCardBeCover(checkItem:CardItem):boolean {
        let beginX:number = Math.max(checkItem.pos.gridX - 1, 0); 
        let beginY:number = Math.max(checkItem.pos.gridY - 1, 0); 
        let endX:number = Math.min(checkItem.pos.gridX + 1, allColumn-1); 
        let endY:number = Math.min(checkItem.pos.gridY + 1, allColumn-1); 
        for (let x:number = beginX; x <= endX; x++) {
            for (let y:number = beginY; y <= endY; y++) {
                if (this.info.allCards.get(`${x}_${y}`) != null){
                    // console.log("这里有卡牌挡住",this.info.layerId, x,y, this.info.allCards.get(`${x}_${y}`));
                    return true;
                }
            }
        }
        return false;
    }



    // /**
    //  * 获取所有卡牌的设置
    //  */
    // public getAllInfo():any {
    //     let resule:any = {layerId:this.info.layerId,cards:[]};
    //     this.info.allCards.forEach((item:CardItem,key:string)=>{
    //         let onCard:any = {type:item.type,gridX:item.pos.gridX, gridY:item.pos.gridY};
    //         resule.cards.push(onCard);
    //     })
    //     return resule;
    // }



    /**
     * 检查这个laya是否已经清光了
     * laya里没用卡牌，并且选中区内也没有相同id的卡牌，就判断为空了，true
     * @param selectCards 当前在选择中区域的剩余卡牌
     * @returns 
     */
    public checkLayerClear(selectCards:CardItem[] = null):boolean {
        let checkLayer:LayerInfo = this.info;
        if (checkLayer.allCards.size == 0) {
            if (selectCards == null || selectCards.length == 0) {
                return true;
            }else{
                for (let index = 0; index < selectCards.length; index++) {
                    let card:CardItem = selectCards[index];
                    if (card.belongLayer.layerId == checkLayer.layerId) {
                        return false;
                    }
                }
                return true;
            }
        }
        return false;
    }





    // private gridNode:cc.Node;
    // private gridPen:cc.Graphics;
    // public drawCell() {
    //     if (this.gridNode == null) {
    //         this.gridNode = new cc.Node();
    //         GlobalContext.Floor.addChild(this.gridNode);
    //         this.gridNode.setAnchorPoint(0, 0);
    //         this.gridNode.setPosition(0, 0);
    //         this.gridPen = this.gridNode.addComponent(cc.Graphics);
    //     }
    //     this.gridPen.clear();
    //     let color;
    //     this.gridPen.strokeColor = cc.Color.BLACK;
    //     this.gridPen.lineWidth = 2;
    //     // this.gridPen.fillColor = cc.Color.TRANSPARENT;
    //     let walkable: boolean;
    //     let dir:number;
    //     let startDrawX: number;
    //     let startDrawY: number;
    //     for (let columnX = 0; columnX < this._hGridNum; columnX++) {
    //         for (let rowY = 0; rowY < this._vGridNum; rowY++) {
    //             walkable = (this.getGridInfo(columnX, rowY).d != EDirection.ED_NULL);
    //             dir = this.getGridDir(columnX, rowY);
    //             startDrawX = columnX * MapTiledSize;
    //             startDrawY = rowY * MapTiledSize;
    //             // console.log("绘制格子", startDrawX, startDrawY);
    //             this.gridPen.rect(startDrawX, startDrawY, MapTiledSize, MapTiledSize);
    //             this.gridPen.stroke();
    //             if (walkable) {
    //                 let color = cc.Color.BLUE.setA(100);
    //                 this.gridPen.fillColor = color;
    //             } 
    //             else {
    //                 let color = cc.Color.RED.setA(100);
    //                 this.gridPen.fillColor = color;
    //             }
    //             this.gridPen.fill();
    //             let x:number;
    //             let y:number;
    //             switch (dir) {
    //                 case EDirection.ED_U:
    //                     x = MapUtil.getFlatByIndexX(columnX);
    //                     y = MapUtil.getFlatByIndexX(rowY);
    //                     this.gridPen.moveTo(x, y);
    //                     this.gridPen.lineTo(x, y + halfMapTiledSize);
    //                     break;
    //                 case EDirection.ED_UR:
    //                     x = MapUtil.getFlatByIndexX(columnX);
    //                     y = MapUtil.getFlatByIndexX(rowY);
    //                     this.gridPen.moveTo(x, y);
    //                     this.gridPen.lineTo(x + halfMapTiledSize, y + halfMapTiledSize);
    //                     break;
    //                 case EDirection.ED_R:
    //                     x = MapUtil.getFlatByIndexX(columnX);
    //                     y = MapUtil.getFlatByIndexX(rowY);
    //                     this.gridPen.moveTo(x, y);
    //                     this.gridPen.lineTo(x + halfMapTiledSize, y);
    //                     break;
    //                 case EDirection.ED_DR:
    //                     x = MapUtil.getFlatByIndexX(columnX);
    //                     y = MapUtil.getFlatByIndexX(rowY);
    //                     this.gridPen.moveTo(x, y);
    //                     this.gridPen.lineTo(x + halfMapTiledSize, y - halfMapTiledSize);
    //                     break;
    //                 case EDirection.ED_D:
    //                     x = MapUtil.getFlatByIndexX(columnX);
    //                     y = MapUtil.getFlatByIndexX(rowY);
    //                     this.gridPen.moveTo(x, y);
    //                     this.gridPen.lineTo(x, y - halfMapTiledSize);
    //                     break;
    //                 case EDirection.ED_DL:
    //                     x = MapUtil.getFlatByIndexX(columnX);
    //                     y = MapUtil.getFlatByIndexX(rowY);
    //                     this.gridPen.moveTo(x, y);
    //                     this.gridPen.lineTo(x - halfMapTiledSize, y - halfMapTiledSize);
    //                     break;
    //                 case EDirection.ED_L:
    //                     x = MapUtil.getFlatByIndexX(columnX);
    //                     y = MapUtil.getFlatByIndexX(rowY);
    //                     this.gridPen.moveTo(x, y);
    //                     this.gridPen.lineTo(x - halfMapTiledSize, y);
    //                     break;
    //                 case EDirection.ED_UL:
    //                     x = MapUtil.getFlatByIndexX(columnX);
    //                     y = MapUtil.getFlatByIndexX(rowY);
    //                     this.gridPen.moveTo(x, y);
    //                     this.gridPen.lineTo(x - halfMapTiledSize, y + halfMapTiledSize);
    //                     break;
    //             }
    //         }
    //     }
    // }


    
}


